package com.zswl.decorate.base;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.BallPulseView;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.lcodecore.tkrefreshlayout.header.SinaRefreshView;
import com.zswl.decorate.R;
import com.zswl.decorate.adapter.WrapRecyclerAdapter;
import com.zswl.decorate.util.RxUtil;
import com.zswl.decorate.widget.SwipeRecyclerView;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;

public abstract class BaseListActivity<B extends BaseBean, A extends BaseRecycleViewAdapter<B>> extends BackActivity implements SwipeRefreshLayout.OnRefreshListener, SwipeRecyclerView.OnLoadListener {
    @BindView(R.id.rv)
    protected RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    protected TwinklingRefreshLayout refreshLayout;
    protected List<B> data;
    protected A adapter;
    private int page;
    protected int limit = 2;
    protected BaseObserver<List<B>> observer;//加载数据回调
    protected boolean isLoadData = true;
    protected boolean isRefresh = true;
    protected WrapRecyclerAdapter adapter1;

    @Override
    protected void init() {
        data = new ArrayList<>();
        initAdapter();
        adapter1 = new WrapRecyclerAdapter(adapter);
//        recyclerView.getRecyclerView().setLayoutManager(getLayoutManager());
        recyclerView.setLayoutManager(getLayoutManager());
//        recyclerView.setOnLoadListener(this);

//        recyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
//        recyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
//        recyclerView.setArrowImageView(R.drawable.iconfont_downgrey);
//
//        recyclerView
//                .getDefaultRefreshHeaderView()
//                .setRefreshTimeVisible(true);
//        View header = LayoutInflater.from(this).inflate(R.layout.recyclerview_header, (ViewGroup) findViewById(android.R.id.content), false);
//        View header1 = LayoutInflater.from(this).inflate(R.layout.recyclerview_header1, (ViewGroup) findViewById(android.R.id.content), false);
//        recyclerView.addHeaderView(header);
//        recyclerView.addHeaderView(header1);
//        adapter1 = new WrapRecyclerAdapter(adapter);
//        recyclerView.setPullRefreshEnabled(false);
//        recyclerView.setLoadingMoreEnabled(true);
//        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
//            @Override
//            public void onRefresh() {
//                isRefresh = true;
//                data.clear();
//                page = 0;
//                getListData(page);
//
//            }
//
//            @Override
//            public void onLoadMore() {
//                isRefresh = false;
//                page = page + limit;
//                getListData(page);
//            }
//        });
        recyclerView.setAdapter(adapter1);
        SinaRefreshView sinaRefreshView = new SinaRefreshView(context);
        refreshLayout.setHeaderView(sinaRefreshView);
        refreshLayout.setBottomView(new LoadingView(context));
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
//                super.onRefresh(refreshLayout);
                isRefresh = true;
                data.clear();
                page = 0;
                getListData(page);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
//                super.onLoadMore(refreshLayout);
                isRefresh = false;
                page = page + limit;
                getListData(page);
            }
        });

//        recyclerView.setOnLoadListener(this);
        observer = new BaseObserver<List<B>>(context, false) {
            @Override
            public void receiveResult(List<B> result) {
//                recyclerView.setRefreshing(false);
//                recyclerView.refreshComplete();
//                refreshLayout.finishRefreshing();
//                refreshLayout.finishLoadmore();
                if (!isRefresh) {
//                    recyclerView.onNoMore("--- 到底了---");
//                    recyclerView.setNoMore(true);
                    data.addAll(result);
//                    adapter.notifyItemRangeInserted(data.size(), result.size());
                    refreshLayout.finishLoadmore();
//                    recyclerView.loadMoreComplete();
                    adapter1.notifyDataSetChanged();
                } else {
//                    recyclerView.setRefreshing(false);
//                    recyclerView.refreshComplete();
                    data.addAll(result);
                    adapter1.notifyDataSetChanged();
                    refreshLayout.finishRefreshing();
                }


            }
        };

//        recyclerView.getSwipeRefreshLayout().setColorSchemeResources(R.color.colorPrimary);


        if (isLoadData)
            getListData(page);
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        Type type = getClass().getGenericSuperclass();
        Class<A> clazz = (Class<A>) ((ParameterizedType) type).getActualTypeArguments()[1];
        try {
            Constructor constructor = clazz.getDeclaredConstructor(Context.class, List.class, int.class);
            adapter = (A) constructor.newInstance(context, data, getItemLayout());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }

    /**
     * 列表布局
     *
     * @return
     */
    protected abstract int getItemLayout();



    /**
     * 获取列表数据
     *
     * @param page
     */
    protected void getListData(int page) {
        if (getApi(page) == null) {
//            recyclerView.setNoMore(true);
            return;
        }
        getApi(page).compose(RxUtil.io_main(lifeSubject))
                .subscribe(observer);
    }


    /**
     * 获取api接口
     *
     * @return
     */

    protected abstract Observable<HttpResult<List<B>>> getApi(int page);

    /**
     * 列表布局管理器
     *
     * @return
     */
    protected RecyclerView.LayoutManager getLayoutManager() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        return layoutManager;
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        data.clear();
        page = 0;
        getListData(page);

    }

    @Override
    public void onLoadMore() {
        isRefresh = false;
        page = page + limit;
        getListData(page);
    }
}
